const app = getApp()
const { API_OK } = require('../../utils/setting')
const { courseDetail, classList, wxRequest, classDetail, getCreditFormWatchVideo } = require('../../api/course')
const { getCreditWithShare } = require('../../api/user')
const { addFavourite, cancelFavourite } = require('../../api/goods')
const { bindUserInfo } = require('../../api/user')
Page({
  data: {
    videoPosition: 'sticky',
    stickyTop: 0,
    userInfo: null,
    activeTabIndex: 0,
    poster: '', // 课程封面
    isBought: true,
    isFavourite: true,
    classList: [], // 课时列表
    courseName: '',
    coursePrice: 0.00,
    originPrice: 0.00,
    purchaseNumber: 0,
    courseDescribe: '',
    classSource: '',
    classSourceType: '',
    credit: 0 // 课程兑换需要的积分
  },
  pageData: {
    refresh: false,
    courseId: null,
    classInfo: null,
    submit: false,
    watchingTime: 0, // 观看时间
    classId: null // 课时 id
  },
  onLoad: function (options) {
    this.setData({
      stickyTop: app.globalData.headerHeight,
      userInfo: app.globalData.userInfo
    })
    wx.showLoading({ title: '拼命加载中', mask: true })
    this.pageData.courseId = options.id
    if (wx.getStorageSync('token')) {
      this.getDetail(options.id)
      this.getClassList(options.id)
    } else {
      app.tokenReadyCallback = () => {
        this.getDetail(options.id)
        this.getClassList(options.id)
      }
      app.getTokenFailedCallback = wx.hideLoading
    }
  },
  async onShow() {
    if (!this.pageData.refresh) return
    wx.showLoading({ title: '拼命加载中', mask: true })
    await this.getDetail(this.pageData.courseId)
    this.pageData.refresh = false
  },
  onUnload() {
    this.timer && clearInterval(this.timer)
  },
  onShareAppMessage() {
    getCreditWithShare()
    return {
      title: this.data.courseName || '课程',
      path: `/pages/course-detail/course-detail?id=${this.pageData.courseId}`
    }
  },
  handleVideoPlay() {
    this.timer = setInterval(() => {
      this.pageData.watchingTime += 1
      if (
        (this.pageData.watchingTime >= Math.floor(this.pageData.classInfo.totalSeconds * 0.8)) &&
        !this.pageData.submit
      ) {
        this.addCredit()
      }
    }, 1000)
  },
  handleVideoPause() {
    this.timer && clearInterval(this.timer)
  },
  /**
   * 看视频获取积分
   */
  async addCredit() {
    if (this.pageData.submit) return
    this.pageData.submit = true
    try {
      const res = await getCreditFormWatchVideo({
        data: {
          courses_id: this.pageData.courseId,
          lesson_id: this.pageData.classInfo.id
        }
      })
      // console.log(res)
      if (res.code === API_OK) {
        wx.showToast({ title: '恭喜获得积分', icon: 'none', duration: 1500 })
        for (let i = 0; i < this.data.classList.length; i++) {
          if (this.data.classList[i].id === this.pageData.classInfo.id) {
            this.data.classList[i].canGetCredit = false
            this.setData({ classList: this.data.classList})
            break
          }
        }
        this.timer && clearInterval(this.timer)
        this.pageData.watchingTime = 0
        this.pageData.submit = false
      } else if (res.code === 400){
        // wx.showToast({ title: res.msg, icon: 'none', duration: 1500 })
        this.pageData.submit = false
        this.timer && clearInterval(this.timer)
        this.pageData.watchingTime = 0
      }
    } catch(err) {
      console.warn(err)
      this.pageData.submit = false
    }
  },
  /**
   * 获取用户信息
   */
  async getUserInfo(e) {
    if (e.detail.errMsg !== 'getUserInfo:ok') return

    try {
      wx.showLoading({ title: '拼命加载中', mask: true })
      const res = await bindUserInfo({
        data: {
          nickname: e.detail.userInfo.nickName,
          avatar: e.detail.userInfo.avatarUrl
        },
        callback: wx.hideLoading
      })
      if (res.code === API_OK) {
        wx.showToast({ title: '授权成功', icon: 'success', duration: 1500 })
        this.setData({ userInfo: JSON.parse(e.detail.rawData) })
      } else {
        wx.showToast({ title: '授权失败，请稍后再试', duration: 1500, icon: 'none' })
      }
    } catch(err) {
      console.warn(err)
      wx.hideLoading()
    }
  },
  changeTab({detail: {index}}) {
    this.setData({ activeTabIndex: index })
  },
  /**
   * 获取课程详情
   * @param {number} id 课程 id
   */
  getDetail(id) {
    courseDetail({ data: {course_id: id} })
      .then(res => {
        // console.log(res)
        if (!Object.keys(wxRequest.queue).length) wx.hideLoading()
        if (res.code === API_OK) {
          this.setData({
            courseName: res.data.course_name,
            coursePrice: res.data.course_price,
            originPrice: res.data.course_deline,
            purchaseNumber: res.data.sold_count,
            courseDescribe: res.data.course_desc,
            isBought: !!res.data.is_buy,
            isFavourite: !!res.data.is_collect,
            poster: res.data.image && res.data.image.length && res.data.image[0].file_path,
            credit: res.data.score_deduct * 1
          })
        }
      })
      .catch(err => {
        console.warn(err)
        if (!Object.keys(wxRequest.queue).length) wx.hideLoading()
      })
  },
  /**
   * 获取课程列表
   * @param {number} id 课程 id
   */
  getClassList(id) {
    classList({ data: { course_id: id, paginate: 15 } })
      .then(res => {
        console.log(res)
        if (!Object.keys(wxRequest.queue).length) wx.hideLoading()
        if (res.code === API_OK) {
          this.setData({
            classList: res.data.map(lesson => {
              return {
                id: lesson.id,
                name: lesson.lesson_name,
                credit: lesson.lesson_score * 1,
                status: lesson.lesson_status,
                // canGetCredit: true,
                duration: `${lesson.lesson_duration / 60 | 0}:${lesson.lesson_duration % 60}`,
                totalSeconds: lesson.lesson_duration,
                playCount: lesson.lesson_twice
              }
            })
          })
        }
      })
      .catch(err => {
        console.warn(err)
        if (!Object.keys(wxRequest.queue).length) wx.hideLoading()
      })
  },
  /**
   * 获取课时信息（视频/图片）
   */
  async getClassDetail({ currentTarget }) {
    wx.showLoading({ title: '拼命加载中', mask: true })
    // this.pageData.classId = currentTarget.dataset.credit * 1 ? currentTarget.dataset.id : null
    this.pageData.classInfo = this.data.classList[currentTarget.dataset.index]
    this.pageData.watchingTime = 0
    this.timer && clearInterval(this.timer)
    try {
      const res = await classDetail({
        data: { lesson_id: currentTarget.dataset.id },
        callback: wx.hideLoading
      })
      // console.log(res)
      if (res.code === API_OK) {
        let index = res.data.lesson_address.lastIndexOf('.')

        this.setData({
          classSource: res.data.url,
          classSourceType: this._isImage(res.data.lesson_address.substr(index + 1))
        })
      }
    } catch(err) {
      console.warn(err)
    }
  },
  /**
   * @description 判断文件是否是图片
   * @param {string} ext 文件后缀名
   */
  _isImage(ext) {
    const IMAGE_EXT = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'svg', 'tiff']
    return IMAGE_EXT.indexOf(ext.toLowerCase()) > 0 ? 'image' : 'video'
  },
  /**
   * 预览图片
   */
  previewImage() {
    wx.previewImage({
      content: this.data.classSource,
      urls: [this.data.classSource],
      success: ()=>{
        wx.showToast({ title: '长按可下载图片', icon: 'none', duration: 1000, mask: false })
      },
      fail: (err)=>{
        console.warn(err)
      },
    })
  },
  /**
   * 加入收藏
   */
  async toggleFavourite() {
    try {
      wx.showLoading({ title: '正在加入收藏', mask: true })
      const res = this.data.isFavourite
      ? await cancelFavourite({
        data: { courses_id: this.pageData.courseId, type: 2 },
        callback: wx.hideLoading
      })
      : await addFavourite({
        data: { courses_id: this.pageData.courseId, type: 2 },
        callback: wx.hideLoading
      })
      console.log(res)
      if (res.code === 200) {
        this.data.isFavourite
          ? wx.showToast({ title: '取消收藏成功', icon: 'success', duration: 1500, mask: true })
          : wx.showToast({ title: '加入收藏成功', icon: 'success', duration: 1500, mask: true })
        this.setData({ isFavourite: !this.data.isFavourite })
      }
    } catch(err) {
      console.warn(err)
    }
  },
  /**
   * 购买课程
   */
  async buy() {
    wx.navigateTo({
      url: `/pages/confirm-order/confirm-order?order_type=course&course_id=${this.pageData.courseId}&image=${this.data.poster}&price=${this.data.coursePrice}&name=${this.data.courseName}&credit=${this.data.credit}`
    })
  }
})
